package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.constant.material.CollectConstants;
import com.usian.common.constant.wmnews.NewAutoScanConstants;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.WmNewsVO;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import sun.util.calendar.LocalGregorianCalendar;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * ClassName: WmNewsServiceImpl
 * Author:   WGG
 * Date:    2022-11-2022/11/17-11:59
 * Version: 1.0
 * Description:
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper,WmNews> implements WmNewsService {
    @Resource
    private WmMaterialMapper wmMaterialMapper;
    @Resource
    private WmNewsMapper wmNewsMapper;
    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //校验参数是否为空
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //校验分页参数
        dto.checkParam();
        //判断用户登录状态
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //设置查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //用户
        queryWrapper.eq(WmNews::getUserId,user.getApUserId());
        //状态
        queryWrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());
        //标题
        queryWrapper.like(dto.getKeyword()!=null ,WmNews::getTitle,dto.getKeyword());
        //频道
        queryWrapper.eq(dto.getChannelId()!=null,WmNews::getChannelId,dto.getChannelId());
        //时间区间
        queryWrapper.between(dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null,WmNews::getCreatedTime,dto.getBeginPubDate(),dto.getEndPubDate());
        Page pageInfo = new Page<>(dto.getPage(),dto.getSize());
        IPage page = page(pageInfo, queryWrapper);
        //返回响应结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)pageInfo.getTotal());
        responseResult.setData(pageInfo.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {

        log.info("WmNewsDto================{}",dto );
        //1.校验参数是否为空
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断用户是否存在
        Integer apUserId = WmThreadLocalUtils.getUser().getApUserId();
        log.info("yong hu id================{}",apUserId );
        if (apUserId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //封装数据
        WmNews wmNews = dto2WmNews(dto);
        wmNews.setUserId(apUserId);
        //得到图片的路径
        if (dto.getImages()!=null) {
            String images = dto.getImages().toString().replace("[", "").replace(" ", "").replace("]", "").trim();
            wmNews.setImages(images);
        }
        log.info("wmNews================{}",wmNews );
        boolean flag=false;
        if (wmNews.getId()==null){
            //添加
            //3.添加wmNews信息到表中
            flag=save(wmNews);
            System.out.println("3.添加wmNews信息到表中"+wmNews);
        }else {
            //修改
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(wmNews.getId()!=null,WmNewsMaterial::getNewsId,wmNews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
            flag=updateById(wmNews);
        }


        if (flag){
            kafkaTemplate.send(NewAutoScanConstants.WM_NEW_AUTO_SCAN_TOPIC,JSON.toJSONString(wmNews.getId()));
        }



        //4.添加WmNewsMaterial信息到表中 设置内容与图片的关系
        //查询当前用户当前内容所有material_id
        //拿到content中所有图片URL
        String content = wmNews.getContent();
        //通过json插件转换成map集合
        List<Map> maps = JSON.parseArray(content, Map.class);
        List<Integer> ids = new ArrayList<>();
        List<String> URL = new ArrayList<>();
        for (Map<String,String> map : maps) {
            if (map.get("type").equals(CollectConstants.TYPE_IMAGE_COLLECT)){
                String url = map.get("value");
                URL.add(url);
            }
        }
        ids=ids(URL,apUserId);
        log.info("list++++++++++++++++++++{}", ids);
        //拿到news_id
        Integer wmNewsId = wmNews.getId();
        //设置material_id,news_id,type到WmNewsMaterial
        wmNewsMaterialMapper.saveWNM(ids,wmNewsId,CollectConstants.WM_NEWS_CONENT_NONE_IMAGE);


        //5.设置封面和图片的关系
        //通过type判断状态
        List<String> url = new ArrayList<>();
       if (dto.getImages().size()>2){
           wmNews.setType(CollectConstants.WM_NEWS_CONENT_MANY_IMAGE);
           url = URL.stream().limit(3).collect(Collectors.toList());
           log.info("url3333+++++++++++++{}",url);
       }else if (dto.getImages().size()<=2){
            wmNews.setType(CollectConstants.WM_NEWS_SINGLE_IMAGE);
            url = URL.stream().limit(1).collect(Collectors.toList());
           log.info("url11111+++++++++++++{}",url);
        }else{
            wmNews.setType(CollectConstants.WM_NEWS_NONE_IMAGE);
           log.info("url0000000+++++++++++++{}",url);
        }
        log.info("URL+++++++++++++{}",URL);

        //修改wmNews表中的字段
        LambdaUpdateWrapper<WmNews> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(WmNews::getId,wmNews.getId());
        updateWrapper.set(WmNews::getType,wmNews.getType());
        updateWrapper.set(WmNews::getImages,url.toString());
        update(updateWrapper);
        ids=ids(URL,apUserId);
        log.info("list++++++++++++++++++++{}", ids);
        //拿到news_id
        //设置material_id,news_id,type到WmNewsMaterial
        wmNewsMaterialMapper.saveWNM(ids,wmNewsId,CollectConstants.WM_NEWS_SINGLE_IMAGE);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult one(Integer id) {
        //校验参数是否为空
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNewsVO one = wmNewsMapper.one(id);
        return ResponseResult.okResult(one);

    }

    @Override
    public ResponseResult delNews(Integer id) {
        //判断id是否为空
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //删除中间表
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId,id);
        wmNewsMaterialMapper.delete(queryWrapper);
        //删除wm_news表
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上 下架
     * @param wmNews
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNews wmNews) {
        //校验参数是否为空
        if (wmNews.getId()==null && wmNews.getEnable()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据条件修改状态
        LambdaUpdateWrapper<WmNews> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(WmNews::getId,wmNews.getId());
        updateWrapper.set(WmNews::getEnable,wmNews.getEnable());
        update(updateWrapper);

        WmNews wmNews1 = getById(wmNews.getId());
        kafkaTemplate.send(NewAutoScanConstants.WM_NEW_AUTO_SCAN_TOPIC2,JSON.toJSONString(wmNews1));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult listWmNews(WmNewsDto wmNewsDto) {
        //判空
        if (wmNewsDto.getTitle()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //校验分页
        wmNewsDto.checkParam();
        Integer page = (wmNewsDto.getPage()-1)* wmNewsDto.getSize();
        List<WmNewsVO> list = wmNewsMapper.listWmNews(wmNewsDto.getTitle(), page, wmNewsDto.getSize());
        Integer count = wmNewsMapper.selectCount(null);
        ResponseResult responseResult = new PageResponseResult(page, wmNewsDto.getSize(), count);
        responseResult.setData(list);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatusAndReason(WmNews wmNews) {
        System.out.println(" public ResponseResult updateStatusAndReason(WmNews wmNews) {======"+wmNews);
         LambdaUpdateWrapper<WmNews> updateWrapper = new LambdaUpdateWrapper<>();
         updateWrapper.set(wmNews.getStatus()!=null,WmNews::getStatus,wmNews.getStatus());
         updateWrapper.set(wmNews.getReason()!=null,WmNews::getReason,wmNews.getReason());
         updateWrapper.set(wmNews.getArticleId()!=null,WmNews::getArticleId,wmNews.getArticleId());
         updateWrapper.eq(WmNews::getId,wmNews.getId());
         update(updateWrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public WmNews getOneWmNews(Integer id) {
            System.out.println("++++++++public WmNews getOneWmNews(Integer id) ============="+id);
        return getById(id);
    }

    @Override
    public List<Integer> findIds() {
        List<WmNews> wmNewsList = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8).lt(WmNews::getPublishTime, new Date()));
        List<Integer> ids = wmNewsList.stream().map(WmNews::getId).collect(Collectors.toList());
        return ids;
    }

    @Override
    public List<Integer> findByStatusIds() {
        return list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus,4)).stream().map(WmNews::getId).collect(Collectors.toList());
    }


    public List<Integer> ids(List<String> URL,Integer apUserId){
        List<Integer> ids = new ArrayList<>();
        //将根据URL查询到图片id 存入ids
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WmMaterial::getUrl,URL);
        queryWrapper.eq(WmMaterial::getUserId,apUserId);
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(queryWrapper);
        //stream流转换成map集合
        Map<String, Integer> collect = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        for (String url : URL) {
//            if (url==null){
//                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
//            }
            Integer id = collect.get(url);
            ids.add(id);
        }
        return ids;
    }


//    封装数据
    public WmNews dto2WmNews(WmNewsDto dto){
        WmNews wmNews = new WmNews();
        wmNews.setId(dto.getId());
        wmNews.setTitle(dto.getTitle());
        wmNews.setContent(dto.getContent());
        wmNews.setChannelId(dto.getChannelId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setPublishTime(dto.getPublishTime());
        wmNews.setLabels(dto.getLabels());
        wmNews.setStatus(dto.getStatus());
        return wmNews;
    }

}
